<?php
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖镇楼                  BUG辟易
//          佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
namespace app\api\controller;

use app\common\logic\Logic;
use app\common\model\MemberConfig;
use app\common\model\Recharge;
use app\common\model\RechargeConfig;
use app\common\service\AppService;
use Carbon\Carbon;
use rongyun\api\RongCloud;
use think\Cache;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use think\Exception;
use think\helper\Time;
use think\Request;
use wheat\Wheat;

class Base extends Controller
{


    //用户id
    protected $user_id = 0;

    protected $checkMember = true;

    /**房间类型数组
     * @var array
     */
    public static $room_type = [
        '1' =>['type_name'=>'电台','type'=>'1'],
        '2' =>['type_name'=>'娱乐','type'=>'2'],
        '3' =>['type_name'=>'点单','type'=>'3'],
        '4' =>['type_name'=>'聊天','type'=>'4'],
    ];

    /**
     * 调用接口时传入的token
     * @var
     */
    protected $token;

    public function _initialize()
    {
//        $array = ['index/online_status','pays/notify','pays/wechat'];

//        $url = request()->controller();
//        $url .= '/'.request()->action();
        $url = strtolower(request()->controller().'/'.request()->action());
        $array = ['index/online_status','index/voice_status','pays/notify','pays/wechat','v1.pays/wechat'];

        if (self::getExplain('closeService') === 'true'){

            if (in_array($url,$array)){
                throw new Exception(self::getExplain('closeMsg'));
            }

            api_return(0,self::getExplain('closeMsg'));
        }

        if (!in_array($url,$array)){

            //不是非拦截请求全部执行限流

            $this->user_id = self::getUserId();

            if ($this->user_id > 0){

                $key = 'key_ip_'.$this->user_id;
            }else{
                $key = 'key_ip_'.request()->ip();
            }

            //接口限流  每3s30次

            $cache = Cache::get($key);
            if (!empty($cache)){
                if (isset($cache['num']) && isset($cache['time'])){
                    if (($cache['time'] - \time()) <= 3){
                        //距离第一次访问不到3s  判断访问次数
                        if ($cache['num'] > self::getExplain('apiLimit')){
                            //3秒访问超过限流参数
                            api_return(0,'访问过于频繁,请稍后重试');
                        }else{
                            //3s超过限流参数   访问数加1
                            $cache['num'] += 1;
                            \cache($key,$cache,3);
                        }
                    }else{
                        //距离第一次访问已超过3s  清除限流参数
                        \cache($key,null);
                    }
                }else{
                    \cache($key,null);
                }

            }else{
                Cache::set($key,['num'=>1,'time'=> \time()],3);
            }

            /**
             * 已登录用户全局处理
             */
            if ($this->user_id > 0){

                $ip = AppService::getUserInfo('ip',$this->user_id);

                $online_status = AppService::getUserInfo('online_status',$this->user_id);

                $update = [];


                //调用接口时如果用户不在线  修改为在线状态
                if ($online_status == 0){
                    $update['online_status'] = 1;
                    $update['online_time']   = time();
                    $update['user_id'] = $this->user_id;
                }

                if ($ip != request()->ip()){
                    $update['ip'] = request()->ip();
                    $update['user_id'] = $this->user_id;
                }

                if (!empty($update)){
                    AppService::pushGlobal('EXTEND',$update);
                }
            }

        }

    }

    /**
     * @param string $url 文件七牛云完整地址
     * @return array
     * $array[code] 查询状态 1=>查询成功  0查询失败
     * $array[msg] 提示信息
     * $array[size] 查询出的文件大小 单位MB
     * $array[data] 第三方返回的信息  用于调试
     */
    public function fileInfo($url = '')
    {
        $array['code'] = 0;
        if (empty($url)){
            $array['msg'] = '文件不存在';
        } else{
            $key = substr($url,(strripos($url,'/')+1));
            $accessKey = config('qiniu.ACCESSKEY');
            $secretKey = config('qiniu.SECRETKEY');
            $bucket = config('qiniu.bucket');
            $auth = new Auth($accessKey, $secretKey);
            $config = new Config();
            $bucketManager = new BucketManager($auth, $config);
            list($fileInfo, $err) = $bucketManager->stat($bucket,$key);
            if ($err) {
                $array['msg'] = '文件信息查询失败';
                $array['data'] = $err;
            } else {
                $array['code'] = 1;
                $array['msg']  = '文件信息查询成功';
                $array['size'] = round($fileInfo['fsize']/1024/1024,2);
                $array['data'] = $fileInfo;
            }
        }
        return $array;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $room_id
     * 获取房间信息
     */
    public function roomInfo($room_id,$field = '',$cache = 3)
    {
        $map['room_id'] = $room_id;
        $map['status']  = 1;

        $data =  Db::name('room')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    public static function StaticRoomInfo($room_id,$field = '',$cache = 3)
    {
        $map['room_id'] = $room_id;
        if ($cache){
            $data =  Db::name('room')->where($map)->cache($cache)->find();
        }else{
            $data =  Db::name('room')->where($map)->find();
        }

        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    public function getChat($user_id,$to_user)
    {
        $map['user_id'] = $user_id;
        $map['to_user'] = $to_user;
        $or['user_id'] = $to_user;
        $or['to_user'] = $user_id;
        return Db::name('first_chat')->field('create_time',true)

            ->where(function ($query)use ($map) {
                $query->where($map);
            })->whereOr(function ($query)use ($or) {
                $query->where($or);
            })
            ->find();
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $field
     * @param bool $array 是否返回数组
     * @param int $cache
     * 获取扩展文本信息
     */
    public static function getExplain($field,$array = false,$cache = 30)
    {
        if ($cache){
            $rows = Db::name('explain')->cache($cache)->select();
        }else{
            $rows = Db::name('explain')->select();
        }



        $data = array_key($rows,'field');
        if (strstr($field,',')){
            $array = true;
        }
        if ($array){
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v]['content'];
            }
            return $array;
        }
        return $data[$field]['content'];
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户扩展信息
     */
    protected function userExtra($field = '',$user_id = null,$cache = 1){
        if ($user_id){
            $map['user_id'] = $user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }
        $data =  Db::name('user_extend')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr   = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户扩展信息
     */
    public static function staticExtra($field = '',$user_id,$cache = 1){

        $map['user_id'] = $user_id;
        $data =  Db::name('user_extend')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 静态获取用户信息
     */
    public static function staticInfo($field = '',$user_id = null,$cache = 1){

        if ($user_id){

            $map['user_id'] = $user_id;

        }else{
            return '';
        }

        $data =  Db::name('users')->where($map)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 查询是否关注房间 可用于判断权限
     */
    public static function roomPower($room_id,$user_id,$now = false)
    {
        $follow['room_id'] = $room_id;
        $follow['user_id'] = $user_id;
        if ($now){
            return Db::name('room_follow')->where($follow)->value('status')??0;
        }
        return Db::name('room_follow')->where($follow)->cache(1)->value('status')??0;
    }


    /**
     * 获取用户会员信息
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param null $user_id
     * @return array|int
     */
    protected function getMember($user_id = null)
    {

        if (!$user_id){
            $user_id = $this->user_id;
        }

        $userInfo = AppService::getUserInfo('nick_name,header_img,is_year,member_time,level',$user_id,false);
        if ($userInfo['member_time'] == 0){
            $userInfo['time'] = '无会员';
        }else{
            Carbon::setLocale('zh');

            if ($userInfo['member_time'] > time()){


                $int = Carbon::now()->diffInYears(date('Y-m-d H:i:s',$userInfo['member_time']),false);

                if ($int >= 10){
                    $str  = '永久会员';
                    $time = '';

                }else{

                    $time = date('Y-m-d H:i',$userInfo['member_time']);

                    $str = '到期时间:';
                }

            }else{
                $str = '已到期:';
                $time = str_replace('后','' ,Carbon::createFromTimestamp($userInfo['member_time'])->diffForHumans());
            }
            $userInfo['time'] = $str.$time;
        }
        return $userInfo;
    }


    public static function getMemberFunc($user_id)
    {
        return (new static)->getMember($user_id);
    }


    /**
     * 会员购买处理
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param int $id
     * @param int $user_id
     * @param bool $pay 是否已付款
     * @return bool|string
     * @throws \think\exception\DbException
     */
    protected function memberHandle($id,int $user_id,$pay = false)
    {
        $userInfo = $this->getMember($user_id);

        if (is_numeric($id)){
            $config = MemberConfig::get($id);
        }elseif ($id instanceof MemberConfig){
            $config = $id;
        }else{
            api_return(0,'会员配置信息查询错误');
        }


        Db::startTrans();
        try{
            if (!$pay){
                $this->moneyDec($config['price']);
            }

            $update = self::getMemberInfo($userInfo,$config);

            Db::name('user_extend')->where('user_id',$user_id)->update($update);
            money_detail(2,$user_id,'会员购买',$config['price']);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }

        return true;
    }


    /**
     * 获取会员信息
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $userInfo
     * @param $config
     * @return mixed
     */
    public static function getMemberInfo($userInfo,$config)
    {
        $update['is_year'] = 0;
        //本身为年费会员且时间未过期  修改年费会员标识
        if ($userInfo['is_year'] == 1 && $userInfo['member_time'] >= time()){
            $userInfo['is_year'] = 1;
        }else if ($config['end_time_num'] >= 86400 * 365){
            //不是年费会员  或会员已过期  判断是否购买的年费会员

            //续费成年费
            $update['is_year'] = 1;
        }

        if ($userInfo['member_time'] >= time()){
            //贵族未过期
            $update['member_time'] = $userInfo['member_time'] + $config['end_time_num'];

        }else{

            $update['member_time'] = time() + $config['end_time_num'];

        }

        return $update;
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 检查贵族是否有效  有效返回贵族id  无效返回0
     *$data => ['user_id','noble_id','noble_time']
     */
    public static function checkNoble($data)
    {
        if ($data['noble_id'] == 0){
            return 0;
        }
        if ($data['noble_time'] < time()){
            //贵族过期  判断是否还有其它贵族存在
            $where['user_id'] = $data['user_id'];
            $where['noble_time'] = ['>',time()];
            $result = Db::name('noble_record')->where($where)->order('noble_id desc')->find();

            if ($result){
                //存在未过期的贵族信息  更新贵族等级
                $update['user_id'] = $data['user_id'];
                $update['noble_time'] = $result['noble_time'];
                $update['noble_id'] = $result['noble_id'];
                AppService::pushGlobal('EXTEND',$update);
            }

            //如果贵族已过期二个月以上 清除用户贵族id 和贵族过期时间 删除创建的聊天房间
            if ($data['noble_time'] < time() + 3600*24*62){

                if (empty($data['user_id']) || !is_numeric($data['user_id'])){
                    api_return(0,request()->url().'checkNoble user_id错误');
                }

                $map['user_id'] = $data['user_id'];
                $map['type']    = 4;
                //贵族过期删除创建的贵族房间
                Db::name('room')->where($map)->delete();

                //清空贵族保护期
                Db::name('user_extend')->where('user_id',$data['user_id'])->update(['noble_id'=>0,'noble_time'=>0]);
            }

            return 0;
        }
        return $data['noble_id'];
    }

    /**
     * 获取贵族id
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function getNobleId($user_id)
    {
        $data = $this->userExtra('noble_time,noble_id,user_id',$user_id);
        return self::checkNoble($data);
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 退出房间
     */
    public static function outRoomFunc($user_id,$room_id)
    {
        if (!$room_id){
            return false;
        }
        //贵族离开房间减少热度
        $info  = self::userExtra('user_id,noble_id,noble_time,room_id',$user_id);
        $noble_id = self::checkNoble($info);
        if ($noble_id == 5 || $noble_id == 4 || $noble_id == 3) {
            if ($noble_id == 5) {
                $hot = 1001;
            } else if ($noble_id == 4){
                $hot = 501;
            }else{
                $hot = 201;
            }
        }else{
            $hot = 1;
        }

        $hotValue = hotValue($room_id);
        if ($info['room_id'] == $room_id){
            delHot($room_id,$hot);
            //通知到房间热度修改
            self::sendRoomMsg($room_id,'hotChange',$hotValue-$hot);
        }

        $roomInfo = self::StaticRoomInfo($room_id);
        //用户上麦成功 或在排麦中 清除排麦数据
        $wheat   = Wheat::wheat($room_id);
        $refresh = false;
        $hash    = hashid($user_id);

        foreach ($wheat as $k => $v){
            //电台房间  主播下麦清空麦序
            if ($roomInfo['type'] == 1){
                if ($wheat[0]['user_id'] == $hash){
                    Wheat::wheatInit($room_id);
                    $refresh = true;
                    goto refresh;
                }
            }


            //娱乐和聊天房间  房主不下麦
            if ($roomInfo['type'] == 2 || $roomInfo['type'] == 4){
                if ($roomInfo['user_id'] == $user_id){

                    continue;
                }
            }

            if ($v['user_id'] === $hash){
                //在麦序上清除麦序信息发送房间麦序推送且循环不继续执行
                $refresh = true;
                $wheat[$k]['user_id']    = "0";
                $wheat[$k]['header_img'] = "";
                $wheat[$k]['nick_name']  = "";
                $wheat[$k]['uuid']       = 0;
                $wheat[$k]['power']      = 4;

                Cache::store('redis')->set('wheat_bit_'.$room_id,$wheat);
                if ($roomInfo['type'] == 3){
                    self::autoWheat($roomInfo['room_id'],$v['wheat_id']);
                }
                break;
            }
        }

        if ($refresh){
            goto refresh;
        }

        $rows1 = cache('1wheatRequest_'.$room_id)??[];

        if (in_array($user_id,$rows1)){
            unset($rows1[$user_id]);
            cache('1wheatRequest_'.$room_id,$rows1,todayEndTime());
        }
        $rows2 = cache('2wheatRequest_'.$room_id)??[];
        if (in_array($user_id,$rows2)){
            unset($rows2[$user_id]);
            cache('2wheatRequest_'.$room_id,$rows2,todayEndTime());

        }

        refresh:
        return $refresh;
    }



    public function _empty()
    {
        api_return(0,'路由错误');
    }

    /**
     * 根据提交的手机号码获取用户id
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @return mixed
     */
    protected function phone_to_id(){
        $phone = input('post.phone');
        $usr = Db::name('users')->where(['phone'=>$phone,'status'=>1])->value('user_id');
        if(!$usr||is_null($usr)){
            api_return(0,'用户信息不存在或被禁用');
        }
        return $usr;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 贵族购买
     */
    protected function nobles($data)
    {

        $price = $data['price'];
        $give  = $data['give'];
        if ($price <= 0) api_return(0,'价格错误');

        $dehash = dehashid($data['user_id']);

        //加上赠送金额
        Db::name('users')->where('user_id',$dehash)->setInc('money',$give);
        money_detail(1,$dehash, '贵族('.$data['noble_name'].')购买赠送',$give,'赠送');
        $update['noble_id']   = $data['noble_id'];
        $update['noble_time'] = $data['noble_time'];

        $str = $data['noble_name'].'开通成功,本次购买赠送了'.$data['price'].'点经验和'.$give.'钻石';
        money_detail(2,$dehash, '贵族('.$data['noble_name'].')购买',$price,'消费');

        self::sendUsrMsg('system',$data['user_id'],$str);

        //更新贵族信息
        Db::name('user_extend')->where('user_id',$dehash)->update($update);

        //参与贵族购买活动
        $this->nobleActSql($dehash,$data['noble_id'],$data['noble_time']);
        return true;
    }

    /**
     * 2019-10-7贵族购买活动
     */
    public function nobleActSql(int $user_id,int $noble_id,int $noble_time): void
    {
        $map['user_id'] = $user_id;
        $map['noble_id'] = $noble_id;
        $id = Db::name('noble_record')->where($map)->value('id');

        if ($id){
            Db::name('noble_record')->where('id',$id)->update(['noble_time'=> $noble_time]);
        }else{
            $map['noble_time'] = $noble_time;
            Db::name('noble_record')->insert($map);
        }
    }



    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 创建token 并存储在缓存中
     */
    protected function makeToken($user_id){

        $hash  = hashid($user_id);
        $key   = md5($user_id.time());
        $token = $hash.'+'.$key;

        $cache['key']     = $key;
        $cache['user_id'] = $user_id;

        cache('token_'.$hash,$cache,time()+config('token_expire'));

        return $token;
    }

    /**
     * 更新用户扩展信息
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $user_id
     * @param null $data
     * @return int|string
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    protected static function updateUserExtend($user_id,$data = null,$update_city = false){
        if (!is_array($data)){
            $data = \request()->only(
                ['log','lat','place','j_push_id','invite','dispatch','filter','hall','wx_name','qq_name','wb_name','LabourUnion','IMEI']
                ,'post');
        }

        if (empty($data)){
            return  false;
        }


        $data['ip'] = \request()->ip();

        if ($update_city){
            $data['city'] = ipToCity($data['ip']);
        }

        $validate = new \app\common\validate\Base();

        if (!$validate->scene('edit_extend')->check($data)){
            api_return(0,$validate->getError());
        }

        $data['user_id'] = $user_id;

        AppService::pushGlobal('EXTEND',$data);

        return true;
//        $result = Db::name('user_extend')->where('user_id',$user_id)->update($data);
//        if ($result === false){
//            //如果更新失败就重复更新一次
//            return Db::name('user_extend')->where('user_id',$user_id)->update($data);
//        }
//        return $result;
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 增加用户经验
     */
    protected function addLevel($experience = 0,$user_id = null)
    {

        if (!$experience) return;
        if (!$user_id){
            $user_id = $this->user_id;
        }

        $extra = $this->userExtra('noble_id,noble_time,user_id',$user_id);

        $noble_id = self::checkNoble($extra);

        if ($noble_id != 0){
            $speed = Db::name('noble')->where('noble_id',$noble_id)->value('speed')??1;
        }else{
            $speed = 1;
        }

        $experience = bcmul($speed,$experience,0);

        $nowLevel = $this->userExtra('level',$user_id);
        $nowExperience = $this->userExtra('experience',$user_id);
        $data = $this->nextLevel($nowLevel,$nowExperience);

        $item['experience'] = bcadd($experience,$nowExperience,0);

        if ($experience >= $data['nextExperience']){
            $maxLevel = Db::name('user_level')->order('level desc')->cache(30)->value('level');

            if ($nowLevel < $maxLevel){
                //达到等级升级经验且当前等级小于最大等级更新大厅VIP等级

                $level = $this->levelNum($item['experience'],$nowLevel);

                if ($level){
                    $item['level'] = $level;
                }
            }
        }
        $result = Db::name('user_extend')->where('user_id',$user_id)->update($item);
        if ($result === false){
            api_return(0,'增加经验失败!');
        }
        return true;
    }


    /**
     * token对比
     * 用于验证是否登陆
     */
    protected function checkToken(){
        $request = Request::instance();
        if ($request->isPost() || $request->isGet()){
            $token = $request->param('token')??$request->header()['token'];
            if (empty($token)){
                api_return(-1,'未登录');
            }

            $this->token = $token;

            $data  = explode('+',$token);

            if (input('test') == 'xiaosong'){
                return (int) dehashid($data[0]);
            }

            $cache = cache('token_'.$data[0]);
            if ($cache && $cache['key'] == $data[1]){
                return $cache['user_id'];
            }else{
                api_return(-1,'登录过期',new EmptyC());
            }
        }
        api_return(0,'访问错误');
    }

    /**
     * 非强制登录情况下获取用户id
     * 用于验证是否登陆
     */
    public static function getUserId($token = null){
        if (!$token){
            $token = request()->param('token')??request()->header()['token'];

            if (empty($token)){
                return 0;
            }
        }
        $data  = explode('+',$token);
        if (input('test') == 'xiaosong'){
            return dehashid($data[0]);
        }
        $cache = cache('token_'.$data[0]);
        if ($cache && $cache['key'] == $data[1]){
            return $cache['user_id'];
        }else{
            return 0;
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取与当前用户相反的性别数字
     */
    protected function getSex($user_id = 0){
        if ($user_id <= 0){
            return 2;
        }
        if ($this->userInfo('sex',$user_id) == 1){
            return 2;
        }else{
            return 1;
        }
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 检查验证码是否正确
     */
    protected function checkCode($field = 'phone',$msg = '验证码错误',$code = 'code')
    {
        if (is_numeric($field)){
            $phone = $field;
        }else{
            $phone = input("post.$field");
        }

        $code  = input("post.$code");


        if ($code == '654321'){
            return true;
        }

        if ($phone == "18782207088" && $code == '123456'){
            return true;
        }

        $cache = cache('code'.$phone);
        if (!$cache || $code != $cache){
            api_return(0,$msg);
        }else{
            cache('code'.$phone,null);
        }
    }



    /**
     * @param int $phone
     * @return bool
     * 检查手机号是否可以注册
     */
    protected function is_register($phone = 0)
    {
        $data   = Db::name('users')->where('phone',$phone)->value('user_id');
        if ($data) return false;
        return true;
    }

    /**
     * 验证昵称是否可用
     */
    protected function exist($nick_name){
        $data  = Db::name('users')->where('nick_name',$nick_name)->value('user_id');
        if ($data){
            return false;
        }else{
            $arr = Db::name('extend')->where('id',1)->value('nick_name');
            $array = explode(',',$arr);
            if (in_array($nick_name,$array)){
                return false;
            }
        }
        return true;
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 查询单独一条数据
     * @param string $db 要操作的数据库
     * @param string|array $map 传入string为单字段筛选根据post获取到的id进行查找  传入array即代表调用方法前已处理数据 直接筛选
     * @param string $field 要查找的数据字段
     * @param bool $type 为false表示查找$field字段 为true表示过滤$field字段
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _find($db = '',$map = '',$field = '', $type = false){
        if (is_array($map)){
            $where = $map;
        }else{
            $id = input('post.id');
            if(is_numeric($id)){
                $where[$map] = $id;
            }else{
                api_return(0,'参数错误');
            }
        }
        return Db::name($db)->field($field,$type)->where($where)->find();
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取单独字段数据
     * @param string $db 要操作的表
     * @param string $field 要获取的字段
     * @param string|array $map 传入string为单字段筛选根据post获取到的id进行查找  传入array即代表调用方法前已处理数据直接查找
     * @return mixed
     */
    protected function _value($db = '',$field = '',$map = ''){
        if (is_array($map)){
            $where = $map;
        }else{
            $id = input('post.id');
            if(is_numeric($id)){
                $where[$map] = $id;
            }else{
                api_return(0,'参数错误');
            }
        }
        return Db::name($db)->where($where)->value($field);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改数据
     */
    public function _edit($table = '',$validate = true,$data = null)
    {

        if (!$data){
            $data = input('post.');
        }
        $model = new Logic();
        $result = $model->saveChange($table,$data,$validate);
        if ($result !== false){
            return true;
        }
        $this->editError = $model->getError();
        return false;
    }

    protected $editError = '系统繁忙,请稍后重试';

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 数据删除
     * @param string $db 要进行操作的数据库
     * @param string $field 要操作的字段名
     * @param bool $type false 假删 true 真删
     * @return int|string
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    protected function _pass($db = '',$field = '',$type = false){
        $id = input('post.id');
        if(is_numeric($id)){
            if ($type){
                return Db::name($db)->where($field,$id)->delete();
            }else{
                return Db::name($db)->where($field,$id)->update(['status' => 0]);
            }
        }
        api_return(0,'参数错误');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * @param string $user_id
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取融云token
     */
    protected function R_token($user_id = '')
    {
//
//        $token  = cache('r_token_'.$user_id);
//        if ($token) return $token;

        //TODO稍后解除融云消息


        $userId     = hashid($user_id);
        $userInfo   = Db::name('users')->where('user_id',$user_id)->field('nick_name,header_img')->find();
        $nick_name  = $userInfo['nick_name']??'游客'.rand(111111,99999);
        $header_img = $userInfo['header_img']??config('default_img');

        $model  = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $model->user()->getToken($userId,$nick_name,$header_img);
        $res    = json_decode($result,true);
        if ($res['code'] == 200){
            if (is_numeric($user_id)) cache('r_token_'.$user_id,$res['token'],86400*7);
            return $res['token'];
        }
        return "";
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据表主键修改单字段状态

     */
    protected function _changeField(string $table,int $pk,$field = 'status',$update = 0){
        $db = Db::name($table);
        return $db->where($db->getPk(),$pk)->update([$field=>$update]);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户信息
     */
    public function userInfo($field = '',$user_id = 0,$cache = 3){

        if ($user_id){

            $map['user_id'] = $user_id;

        }else{

            $map['user_id'] = $this->user_id;

        }

        return AppService::getUserInfo($field,$map['user_id'],$cache);
//        $data =  Db::name('users')->where($map)->cache($cache)->find();
//        if (strstr($field,',') || empty($field)){
//            if (!$field){ return $data; }
//            $arr   = explode(',',$field);
//            $array = [];
//            foreach ($arr as $v){
//                $array[$v] = $data[$v];
//            }
//            return $array;
//        }else{
//            return $data[$field];
//        }

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * @param $user_id
     * 登录日志
     */
    public function log($user_id,$sex = 1)
    {

        //登陆日志
        $log['ip'] = request()->ip();
        $log['IMEI'] = input('IMEI');
        $log['version'] = input('version');
        $log['sex']  = $sex;
        if (empty(input('post.model'))){
            $log['model'] = 'web';
        }else{
            $log['model'] = input('post.model');
        }

        $log['user_id']     = $user_id;
        $log['create_time'] = time();
        Db::name('login_log')->strict(false)->insert($log);
    }

    /**
     * @param $room_id string  要发送到的聊天室id
     * @param $type   int  消息类型 详见switch注释
     * @param $rows  array 消息主体内容
     *
     *  $rows 解释
     *  gift  礼物消息
     *  $rows[gift_name]  礼物名称
     *  $rows[img]  礼物图片地址
     *  $rows[num]  送礼数量
     *  $rows[role_name]  送礼者角色名
     *  $rows[role_id]  送礼者加密后角色id
     *
     *    refreshWheat  刷新麦序消息
     *  $rows[gift_name]  礼物名称
     *  $rows[img]  礼物图片地址
     *  $rows[num]  送礼数量
     *  $rows[role_name]  送礼者角色名
     *  $rows[role_id]  送礼者加密后角色id
     *
     * 融云自定义消息房间消息发送
     */
    public function sendRoomMsg($room_id,$type,$rows = []){
        $model = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);

        if ($room_id == 'all'){
            $room_ids = Db::name('room')->where('status',1)->cache(300)->column('room_id');
        }else{
            $room_ids = [$room_id];
        }

        $content = json_encode(['content'=>$rows,'extra'=>$type]);

        return $model->message()->publishChatroom('system',$room_ids, 'RC:system',$content);
    }


    protected function getHiddenUser()
    {
        if (get_device_type() == 'ios'){
            $filed = 'hidden_user_ios';
        }else{
            $filed = 'hidden_user';
        }

        $users = explode(',',self::extend($filed));

        if (empty($users)){
            return false;
        }

        $users = array_unique($users);

        $users = array_map(function ($val){
            return (int) $val;
        },$users);
        sort($users);
        return $users;

    }

    protected function addHiddenUser(array $hiddenUser,array $addUser):array
    {
        $users = array_unique(array_merge($hiddenUser,$addUser));
        $users = array_map(function ($val){
            return (int) $val;
        },$users);
        sort($users);
        return $users;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $user_id =>接收消息用户
     * @param $type
     * @param array $rows
     * @return mixed
     * 融云自定义用户消息发送
     */
    public static function sendUsrMsg($fromUser,$user_id,$content = [],$extra = ['type'=>'text','data'=>null]){
        $model   = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $content = json_encode(['content'=>$content,'extra'=>$extra]);
        if (!is_array($user_id)){
            $user_id = [$user_id];
        }
        return $model->message()->publishPrivate($fromUser,$user_id,'RC:TxtMsg',$content, 'thisisapush', '{\"pushData\":\"hello\"}', '4', '0', '0', '0', '0');
    }




    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能统计
     */
    protected static function orderCount(array $map) :array
    {

        $data['num'] = Db::name('order')->where($map)->cache(10)->count();

        $score = Db::name('order')->where($map)->cache(10)->avg('score');

        $data['score'] = numberDecimal($score);

        return $data;
    }




    /**
     * 房间禁言名单获取
     */
    protected function banList($room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result    =  $RongCloud->group()->lisGagUser($room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)

            return $json['users'];
        return false;
    }

    /**
     * 禁言
     */
    protected function ban($room_id,$role_id,$time = 10)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result    = $RongCloud->group()->addGagUser($role_id, $room_id, $time);
        $json      = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }
    
    
    /**
     * 解除禁言
     */
    public function pick($role_id,$room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->group()->rollBackGagUser([$role_id], $room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * 聊天室禁言
     */
    protected function chatban($room_id,$role_id,$time = 10)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->chatRoom()->addGagUser($role_id, $room_id, $time);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * 聊天室禁言名单获取|检查某个用户在当前房间是否被禁言
     */
    protected function chatbanList($room_id,$user_id = 0)
    {
        if ($user_id){
            if (is_numeric($user_id)) $user_id = hashid($user_id);
            $cache = cache('chat_'.$room_id.'_'.$user_id);
            if ($cache) return $cache;
        }else{
            $cache = cache('banlist_'.$room_id);
            if ($cache) return $cache;
        }
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result    =  $RongCloud->chatRoom()->ListGagUser($room_id);
        $json      = json_decode($result,true);
        if ($json['code'] == 200){
            if ($user_id){
                $rows = array_key($json['users'],'userId');
                $data = isset($rows[$user_id]);
                cache('chat_'.$room_id.'_'.$user_id,$data,5);
                return $data;
            }
            cache('banlist_'.$room_id,$json['users'],5);
            return $json['users'];
        }
        return false;
    }


    /**
     * 聊天室解除禁言
     */
    public function chatpick($role_id,$room_id)
    {
        $RongCloud = new RongCloud(config('rongyun')['appKey'],config('rongyun')['appSecret']);
        $result = $RongCloud->chatRoom()->rollBackGagUser([$role_id], $room_id);
        $json = json_decode($result,true);
        if ($json['code'] == 200)
            return true;
        return false;
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 接口单独限流
     */
    protected function ApiLimit($time = 1,$id = 0,$msg = '请求过于频繁,请稍后重试')
    {
        $key   = request()->path().$id;
        $cache = cache('apiLimit'.$key);
        if ($cache){
            api_return(0,$msg);
        }else{
            cache('apiLimit'.$key,1,$time);
        }
    }




    /**
     * @param int $id
     * 销毁限流参数
     */
    protected function destroyLimit($id = 0){
        $key   = request()->path().$id;
        cache('apiLimit'.$key,null);

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取系统扩展信息
     */
    public static function extend($field = '',$cache = 15){

        $data =  Db::name('extend')->where('id',1)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr   = explode(',',$field);
            $array = [];
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
            return $array;
        }else{
            return $data[$field];
        }
    }


    protected static function checkBank($data){

        if (self::getExplain('checkBankCard') === 'open'){
            $data['key'] = \config('juhe')['BankKey'];

            $param = http_build_query($data);
            $url = 'http://v.juhe.cn/verifybankcard3/query?'.$param;
            $result = curl_get($url);
            if (is_zero($result['error_code'])){
                //请求成功
                if ($result['result']['res'] == 1){
                    //匹配成功
                    return true;
                }else{
                    return $result['result']['message'];
                }
            }else{
                return $result['reason'];
            }
        }
        return true;
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param $room_id =>  房间id
     * @param $refreshPower  => 是否刷新麦序上权限
     * 刷新麦序
     */
    public static function refreshWheat($room_id,$refreshPower = false)
    {
        $data = Wheat::wheat($room_id);

        if ($refreshPower){
            foreach ($data as $k => $v){

                if (!is_zero($v['user_id'])){

                    $data[$k]['power'] = getPowerCode($v['user_id'],$room_id,true);
                }
            }
            Wheat::setWheat($room_id,$data);
        }
        self::sendRoomMsg($room_id,'refreshWheat',$data);
    }

    /**
     * 点单房间自动上麦方法
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public  function autoWheat(int $room_id,int $wheat_id)
    {
        $wheat = new Wheat();
        $list = cache('2wheatRequest_'.$room_id);

        if ($list && $wheat_id != 1 && $wheat_id != 9){
            $user_id = reset($list);
            $ret = $wheat->embrace($user_id,$room_id,$wheat_id,getPowerCode($user_id,$room_id));
            if($ret['code']){
                unset($list[$user_id]);
                if(is_array($list)){
                    $num = count($list);
                }else{
                    $num = 0;
                }
                cache('2wheatRequest_'.$room_id,$list,todayEndTime());
                $this->sendRoomMsg($room_id,'wheatRequest2',['num'=>$num,'type'=>2,'user_id'=>hashid($user_id)]);
            }
        }else{
            $wheat->down($room_id,$wheat_id);
        }

    }


    
    
    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 礼物赠送
     */
    protected  function giveGift(array $data,$user_id = null ) :array
    {
        if (!$user_id){
            $user_id = $this->user_id;
        }

        $map['gift_id'] = $data['id'];
        $map['status']  = 1;
        $gift = Db::name('gift')->where($map)->find();

        if (!$gift || $gift['price'] <= 0 ) api_return(0,'参数错误');

        if (!isInt($data['num'])) api_return(0,'赠送数量错误');

        if (empty($data['to_user'])) api_return(0,'请选择要赠送的的人');

        //获取要赠送的人数
        $people = count(explode(',',$data['to_user']));

        //根据礼物单价和赠送数量计算单个人收礼金额

        $total = bcmul($gift['price'],$data['num'],2);

        if ($total <= 0) api_return(0,'赠送金额错误');

        $price = bcmul($total,$people,2);

        $subject = '伴心礼物('.$gift['gift_name'].')赠送';

        $array = [
            'subject'   => $subject, //标题
            'user_id'   => hashid($user_id), //赠送用户id
            'id'        => $data['id'], //礼物id
            'type'      => $data['type'],
            'to_user'   => $data['to_user'], //接收者
            'room_id'   => $data['room_id']??0,
            'total'     => $total, //单个人接收礼物总价
            'price'     => $price, //所有礼物总价
            'num'       => $data['num'],
            'allNum'    => $people * $data['num'],//所有礼物总数
            'onePrice'  => $gift['price'],//单个礼物价格
            'countInfo' => $data['countInfo'],
            'is_lock'   => $data['is_lock']??0
        ];

        return $array;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单退款
     */
    public static function refund($data,$status = 6){


        if (is_numeric($data)){
            $data = Db::name('order')->where('order_id',$data)->find();
        }

        $array = [1,2,3,7,9];

        if (!in_array($data['status'],$array)){
            return '订单状态不允许退款';
        }

//        switch ($data['pay_way']){
//
//            case 1: //积分
//
//                $result = Db::name('users')->where('user_id',$data['user_id'])->setInc('money',$data['price']);
//                if (!$result){
//                    return '服务器繁忙,请稍后重试';
//                }
//                money_detail(1,$data['user_id'],'订单退款',$data['price'],'退款');
//
//                break;
//            case 2://支付宝
//
//                $order = [
//                    'out_trade_no' => $data['trade_no'],
//                    'refund_amount' => $data['out_price'],
//                ];
//
//                $result =  Pays::aliRefund($order);
//
//                if (!$result){
//                    return Pays::$errorMsg;
//                }
//
//                break;
//            case 3://微信
//                $order = [
//                    'out_trade_no'  => $data['trade_no'],
//                    'out_refund_no' => $data['out_trade_no'],
//                    'total_fee'     => $data['out_price']*100,
//                    'refund_fee'    => $data['out_price']*100,
//                    'refund_desc'   => '订单退款',
//                ];
//                Pays::weChatRefund($order);
//                break;
//            default:
//                return '无此支付方式';
//                break;
//
//        }
        $result = Db::name('users')->where('user_id',$data['user_id'])->setInc('money',$data['price']);
        if (!$result){
            return '服务器繁忙,请稍后重试';
        }
        money_detail(1,$data['user_id'],'订单退款',$data['price'],'退款');
        money_detail(2,$data['to_user'],'订单退款',$data['price'],'退款');
        Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>$status]);

        $skill_name = Db::name('skill')->where('skill_id',$data['skill_id'])->value('skill_name');
        $form_name  = Db::name('skill_form')->where('form_id',$data['form_id'])->value('form_name');

        $str = sprintf('您发起的与%s %s[%s] 订单已取消,已退款至余额',self::userInfo('nick_name',$data['to_user']),$skill_name,$form_name);
        //发送系统消息
        self::sendUsrMsg('system',hashid($data['user_id']),$str);

        $str = sprintf('%s发起的 %s[%s] 订单已取消,已退款至余额',self::userInfo('nick_name',$data['user_id']),$skill_name,$form_name);
        self::sendUsrMsg('system',hashid($data['to_user']),$str);


        return true;
    }


    public static function rechargeRecord(array $data)
    {
        $item['user_id']     = $data['user_id'];
        $item['money']       = $data['money'];
        $item['remark']      = $data['remark'];
        $item['trade_type']  = isset($data['trade_type'])? $data['trade_type'] :$data['type'];
        $item['pay_money']   = isset($data['pay_money']) ? $data['pay_money'] :$data['money'];
        $item['is_first']    = isset($data['is_first']) ? $data['is_first'] :0;
        $item['pay_type']    = isset($data['pay_type']) ? $data['pay_type'] :0;
        $item['status']      = 1;
        $item['type']        = 1;
        $item['create_time'] = time();
        $item['update_time'] = time();

        Db::name('bankroll')->strict(false)->insert($item);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单完成
     */
    public static function complete($order,$status = 5,$record_str = '')
    {
        //邀约抽成比例
        $invite = self::extend('invite_ratio')??1;

        $ratio = $invite/100;

        //抽成后订单金额
        $money = bcsub($order['price'],bcmul($order['price'],$ratio,2),2);

        $nick_name = self::staticInfo('nick_name',$order['user_id']);

        $skill_name = Db::name('skill')->where('skill_id',$order['skill_id'])->cache(300)->value('skill_name');

        Db::startTrans();
        try{

            Db::name('users')->where('user_id',$order['to_user'])->setInc('cash',$money);

            money_detail(1,$order['to_user'],'和 '.$nick_name.' '.$skill_name.' 完成',$money,'解锁',$order['order_id']);
            money_detail(2,$order['user_id'],'和 '.self::staticInfo('nick_name',$order['to_user']).' '.$skill_name.' 完成',$order['price'],'解锁',$order['order_id']);

            //增加技能完成单数
            $where['skill_id'] = $order['skill_id'];
            $where['user_id']  = $order['to_user'];
            Db::name('skill_apply')->where($where)->setInc('num');

            //增加形式完成单数
            $map['form_id']  = $order['form_id'];
            $map['user_id']  = $order['to_user'];
            $map['status']   = 1;
            $map['skill_id'] = $order['skill_id'];
            Db::name('skill_form_user')->where($map)->setInc('num');

            $update['status'] = $status;
            $update['update_time'] = \time();
            if ($record_str){
                $update['record_str'] = $record_str;
            }

            Db::name('order')->where('order_id',$order['order_id'])->update($update);

            $record['gift_id'] = $order['gift_id'];
            $record['num']     = $order['num'];
            $record['user_id'] = $order['user_id'];
            $record['to_user'] = $order['to_user'];
            $record['total']   = $order['price'];
            $record['order_id'] = $order['order_id'];
            $record['create_time'] = time();
            $record['update_time'] = time();
            Db::name('gift_record')->strict(false)->insert($record);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 开通守护
     * @param array $data
     * @param array $data[type] 开通守护类型
     * @param array $data[user_id] 开通守护人
     * @param array $data[guard_user] 被守护人
     * @param int $$pay 是否已付款
     */
    protected  function guardOpen($data,$pay =  null){


        if (!$pay){
            $price = $this->guard_price($data['type']);
            $data  = $this->checkGuard($data);

            $data['price'] = $price;
        }else{
            $price = $data['price'];
        }

        $map['user_id']    = $data['user_id'];
        $map['guard_user'] = $data['guard_user'];
        $map['type']       = $data['type'];

        $logic  = new Logic();
        $logic->changeTable('user_guard');

        $item = $logic->where($map)->find();

        $data['end_time'] = time() + Time::weekToSecond();

        $data['open_type'] = 1;

        if ($item){
            $data['id'] = $item[$logic->getPk()];
            if ($item['end_time'] > time()){
                $data['end_time']  = $item['end_time'] + Time::weekToSecond();
                $data['open_type'] = 2;
            }
        }
//        dd($data);
        Db::startTrans();
        try{
            if (!$pay){
                $this->moneyDec($price);
            }
            $logic->saveChange('user_guard',$data,false);

            if ($data['type'] == 1){
                $name = '青铜守护';
            }elseif ($data['type'] == 2){
                $name = '白银守护';
            }else{
                $name = '黄金守护';
            }

            $money  = bcsub($price,bcmul($price,$this->extend('guard_ratio')/100,2),2);
            $title  = sprintf('%s开通%s',$this->userInfo('nick_name',$data['user_id']),$name);
            $title2 = sprintf('开通%s的%s',$this->userInfo('nick_name',$data['guard_user']),$name);
            money_detail(1,$data['guard_user'],$title,$money,'收入');
            money_detail(2,$data['user_id'],$title2,$price,'消费');
            Db::name('users')->where('user_id',$data['guard_user'])->setInc('cash',$money);

            if ($data['id']){
                unset($data['id']);
            }
            $data['create_time'] = \time();
            $data['update_time'] = \time();

            //记录开通时   如果有id就删除掉  防止报错
            Db::name('guard_record')->strict(false)->insert($data);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();

            return $e->getMessage();
        }
        //发送系统消息
        $str = sprintf('%s已经开通了你的[%s]现在开始聊天吧',$this->userInfo('nick_name',$data['user_id']),$name);

        self::sendUsrMsg('system',hashid($data['guard_user']),$str,['type'=>'guard','data'=>hashid($data['user_id'])]);

        $content = sprintf('我已经开通了你的[%s]现在开始聊天吧',$name);
        self::sendUsrMsg(hashid($data['user_id']),hashid($data['guard_user']),$content);
        return true;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 检查是否能开通守护
     */
    protected function checkGuard(array $data)
    {
        if (!is_numeric($data['guard_user'])){
            $data['guard_user'] = dehashid($data['guard_user']);
        }

        if (!is_numeric($data['guard_user'])){
            api_return(0,'用户id错误');
        }

        if ($data['guard_user'] == $data['user_id']){
            api_return(0,'您不能守护您自己');
        }

        return $data;

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 守护价格获取及验证
     * @param string $type 开通守护类型
     */
    protected function guard_price($type)
    {
        if (!is_numeric($type)){
            api_return(0,'类型错误');
        }
        $price = $this->extend('guard_'.$type);

        if (!is_numeric($price) || $price < 1){
            api_return(0,'参数错误');
        }

        return $price;
    }

    public static function replaceDatabaseStr(string $keywords,string $replace)
    {
        /* 设置永不超时 */
        ini_set('max_execution_time', 0);
        $tables = Db::query("SHOW TABLES FROM ".config('database.database'));
        $index  = 0;
        $sum    = 0;
        foreach ($tables as $k => $v){ //循环查询表数据
            $pk = db(str_replace(config('database.prefix'),'',$v['Tables_in_yuewan']))->getPk();
            $rows = Db::table($v['Tables_in_yuewan'])->select();
            foreach ($rows as $r => $i){ //循环每条表数据
                $not = false;
                foreach ($i as $m => $item){ //循环数据数组查询是否有需要替换的数据
                    if (strpos($item,$keywords) !== false){ //查询到有需要进行替换的数据  执行替换
                        $sum++;
                        $not = true;
                        $i[$m] = str_replace($keywords,$replace,$item);
                    }
                }
                if ($not){ //有替换内容  执行sql
                    if ($result = Db::table($v['Tables_in_yuewan'])->where($pk,$i[$pk])->update($i)){
                        $index++;
                    };
                }
            }
        }
        exit(sprintf("共执行%u条SQL,包含%u处修改",$index,$sum));
    }


    /**
     * 订单评价
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public  function orderAnonymous($data,$user_id = null)
    {

        if (!isInt($data['score'])){
            api_return(0,'评分需为整数'.$data['score']);
        }

        $map['order_id'] = $data['id'];

        if ($user_id){
            $map['user_id']  = $this->user_id;
        }

        $map['status'] = 4;

        $model = new \app\common\model\Order();

        $order = $model->where($map)->find();
        if (!$order){
            return '订单查询错误';
        }

        $where['skill_id'] = $order['skill_id'];
        $where['user_id']  = $order['to_user'];

        $apply     = Db::name('skill_apply')->where($where)->field('score,score_num,apply_id')->find();
        $score_num = $apply['score_num']+1;

        $score = bcdiv(bcmul($apply['score'],$apply['score_num'],2)+$data['score'],$score_num,1);

        $change['score']       = $score;
        $change['score_num']   = $score_num;
        $change['update_time'] = time();

        $tags = explode(',',$data['tags']);

        $tag['skill_id'] = $order['skill_id'];
        $tag['user_id']  = $order['to_user'];

        Db::startTrans();
        try{

            //订单表修改
            $data['status'] = 5;
            $validate = new \app\common\validate\Order();
            $check = $validate->scene('evaluate')->check($data);
            if ($check === false){
                return $validate->getError();
            }
            $result = $order->allowField(true)->save($data);
            if ($result === false){
                return $order->getError();
            }

            //修改用户技能统计数据
            Db::name('skill_apply')->where('apply_id',$apply['apply_id'])->update($change);

            //修改用户技能评论标签
            $insert_tag = [];
            foreach ($tags as $k => $v){

                $tag['tag'] = $v;
                $user_tag = Db::name('skill_tag_user')->where($tag)->find();
                if ($user_tag){
                    Db::name('skill_tag_user')->where('id',$user_tag['id'])->setInc('num');
                }else{
                    $tag['num'] = 1;
                    $tag['create_time'] = time();
                    $tag['update_time'] = time();
                    $insert_tag[] = $tag;
                }
            }

            if ($insert_tag){
                Db::name('skill_tag_user')->insertAll($insert_tag);
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
        return true;

    }

    /**
     * 门槛费
     * @param $body
     * @param $total
     * @param $type
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function join($body,$total,$type)
    {
        if (is_numeric($body['user_id'])){
            $user_id = $body['user_id'];
        }else{
            $user_id = dehashid($body['user_id']);
        }

        Db::name('users')->where('user_id',$user_id)->update(['is_pay'=>1]);

        $record['user_id']    = $user_id;
        $record['money']      = $total;
        $record['remark']     = $body['subject'];
        $record['type']       = $type;
        $record['trade_type'] = isset($body['trade_type'])? $body['trade_type'] : $body['type'];
        self::rechargeRecord($record);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 充值回调成功处理
     */
    protected function recharge($data,$type = 1)
    {
        if (is_numeric($data['user_id'])){
            $user_id = $data['user_id'];
        }else{
            $user_id = dehashid($data['user_id']);
        }

        if (!is_numeric($user_id))  return false;

        if ($data['id'] instanceof RechargeConfig){
            $config = $data['id'];
        }else{
            $map['r_id']   = $data['id'];
            $map['status'] = 1;
//
            $config = Db::name('recharge_config')->where($map)->cache(3)->find();
        }




//        $item['user_id']     = $user_id;
//        $item['money']       = $config['money'];
//        $item['remark']      = $data['remark'];
//        $item['status']      = 1;
//        $item['type']        = 1;
//        $item['create_time'] = time();
//        $item['update_time'] = time();
//        $item['trade_type']  = $type;
//        $item['pay_money']   = $data['money'];
//
//        Db::name('bankroll')->strict(false)->insert($item);

//        $phone = $this->userInfo('phone',$user_id);
//        $val['val1'] = substr($phone,-4,4);
//        $val['val2'] = $config['money'];

        $str = sprintf('您已成功充值%s钻，赶快进入App使用吧！如有疑问请及时与我们联系。',$config['money']);
        self::sendUsrMsg('system',hashid($user_id),$str);
//        sendCustomSms($phone,$val,'recharge');
        //砸蛋活动开启时赠送锤子
//        $info = self::getExplain('giveOpen,givePrice');
//        if ($info['giveOpen'] === 'open'){
//            $num = bcdiv($config['money'],$info['givePrice'],0);
//            //查询是否为首次充值
//            $con['user_id'] = $user_id;
//            $con['type']    = 1;
//            $first = Db::name('bankroll')->where($con)->count();
//            if ($first == 0){
//                if ($num > 0){
//                    Db::name('users')->where('user_id',$user_id)->setInc('hammer_give');
//                    $str = '首次充值赠送了1个幸运锤,赶快进入砸蛋活动使用吧!';
//                    self::sendUsrMsg('system',hashid($user_id),$str);
//                }
//            }
//        }

        $record['user_id']    = $user_id;
        $record['money']      = $config['money'];
        $record['remark']     = $data['remark'];
        $record['type']       = $type;
        $record['pay_money']  = isset($data['pay_money'])? $data['pay_money']   : $config['price'];
        $record['trade_type'] = isset($data['trade_type'])? $data['trade_type'] : $data['type'];
        $record['is_first']   = isset($data['is_first'])? $data['is_first'] : 0;
        $record['pay_type']   = isset($data['pay_type'])? $data['pay_type'] : 0;
        self::rechargeRecord($record);

        return Db::name('users')->where('user_id',$user_id)->setInc('money',$config['money']);
    }

}
